<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Email_sender extends MY_Email {
	var $CI;
	var $fromEmail = "";
	var $toEmail = "";
	var $subject = "";
	var $body = "";
	var $emailTitle = "";
	
	function __construct( $config = array() ){
		parent::__construct($config);
		
		$this->CI = & get_instance();
		$this->CI->load->library('module_helper');
		
		$this->setFromEmail(Settings_class::get('server_email'));
		$this->setEmailTitle("Clicxa Cricket Prediction Game");
	}	
	
	function setFromEmail($input){$this->fromEmail = $input;}
	function setToEmail($input){$this->toEmail = $input;}
	function setSubject($input){$this->subject = $input;}
	function setBody($input){$this->body = $input;}
	function setEmailTitle($input){$this->emailTitle = $input;}
	
	function sendEmail(){
		$this->from($this->fromEmail, $this->emailTitle);
		$this->to($this->toEmail);
		$this->subject($this->subject);
		$this->message($this->body);
		
		if( ENVIRONMENT != 'local' ){
			$this->send();
		}else{
			$this->sendEmail2();
		}	
	}
	
	function sendEmail2(){
		require_once("PHPMailer/class.phpmailer.php");
		
		try {
			$mail = new PHPMailer(true); 
			$mail->IsSMTP(); // telling the class to use SMTP
			$mail->SMTPDebug  = 0; // enables SMTP debug information (for testing)               
			$mail->SMTPAuth   = true;                  // enable SMTP authentication
			$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
			$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
			$mail->Port       = 465;   
			
			if(ENVIRONMENT != 'local'){
				$mail->Username   = 'clicxatest@gmail.com';
				$mail->Password   = "vicky12@";
			}else{
				$mail->Username   = "dangdinhhung241288@gmail.com";     // SMTP server username
				$mail->Password   = "123123911";            // SMTP server password
			}

			$mail->From       = $this->fromEmail;
			$mail->FromName   = $this->emailTitle;

			$to = $this->toEmail;

			$mail->AddAddress($to);

			$mail->Subject  = $this->subject;
			$body = $this->body;
			$mail->MsgHTML($body);

			$mail->IsHTML(true); // send as HTML

			$mail->Send();
			//echo 'Message has been sent.';
		} catch (phpmailerException $e) {
			//echo $e->errorMessage();
		}
	}
	
	// 1. Send email to friend of user to invite join Clicxa.
	// slug: refer_a_friend
	function _sendEmailToUser_invite($userId, $friendEmail, $friendName, $msg){
		$USER = clone_( $this->CI->user_entity->init('id',$userId) );
		$slug = "refer_a_friend";
		
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		$orgArr = array( "{###NAME###}" ,"{###LINK###}", "{###MSG###}" );
		
		$rplArr = array( $friendName ,site_url( "cricket/user/refer_confirm?code=".$USER->getReferralCode() ), $msg );
		
		$body = str_replace( $orgArr , $rplArr , $template['body'] );
		$subject = $template['subject'];
		
		$this->setToEmail($friendEmail);
		$this->setSubject($subject);
		$this->setBody($body);
		
		$this->sendEmail();
	}
	
	// 2. Send email to user forgot details
	// slug: send_email_to_user_forgot_details
	function _sendEmailToUser_forgot_details($userId){
		$USER = clone_( $this->CI->user_entity->init('id',$userId) );
		$slug = "send_email_to_user_forgot_details";
		
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		$orgArr = array( "{###USERNAME###}", "{###PASSWORD###}" );
		
		$rplArr = array( $USER->getUserName() , $USER->getPasswd() );
		
		$body = str_replace( $orgArr , $rplArr , $template['body'] );
		$subject = $template['subject'];
		
		$this->setToEmail($USER->getEmail());
		$this->setSubject($subject);
		$this->setBody($body);
		
		$this->sendEmail();
	}
	
	// 3. send email notify match is coming
	// slug: email_notification_crontab
	function _sendEmailToUser_notifyMatchComing($userId, $match_id){
		$USER = clone_( $this->CI->user_entity->init('id',$userId) );
		$MATCH = $this->CI->match_entity->init('id', $match_id);
		
		$slug = "email_notification_crontab";
		
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		
		$orgArr = array( "{###MATCH###}" );
		$rplArr = array( $MATCH->getTitle() );
		$body = str_replace( $orgArr , $rplArr , $template['body'] );
		
		$subject = $template['subject'];
		
		$this->setToEmail($USER->getEmail());
		$this->setSubject($subject);
		$this->setBody($body);
		
		$this->sendEmail();
	}
	
	// 4. send email and sms to user notify COD dispatched
	// slug:email_notify_cod_dispatched - send_sms_notify_cod_dispatched
	function _sendEmailToUser_notifyCODdispatched($item_id){
		$COD = clone_($this->CI->cod_data_entity->init('id', $item_id));
		$USER = clone_($this->CI->user_entity->init('id',$COD->getUserId()));
		$PACKAGE = clone_($this->CI->coin_packages_entity->init('id',$COD->getPackageId()));
		
		$slug = "email_notify_cod_dispatched";
		
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		$orgArr = array( "{###ID###}", "{###PACKAGE###}" );
		$rplArr = array( $COD->getId() , $PACKAGE->getPackage() );
		
		$body = str_replace( $orgArr , $rplArr , $template['body'] );
		$subject = $template['subject'];
		
		$this->setToEmail($USER->getEmail());
		$this->setSubject($subject);
		$this->setBody($body);
		
		$this->sendEmail();
		
		$slug = "email_notify_cod_dispatched";
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		$body = $template['body'];
		
		sendSMS($USER->getCodMobile(), $body);
	}
	
	// 5. send email to user notify tournament is finished and prize information
	// slug:
	function _sendEmailToUsers_notifyTournamentFinished($tournament_id){
		$TOURNAMENT = $this->CI->tournament_entity->init('id', $tournament_id);
		$prize_array = $this->CI->prize_entity->getArrayListOfPrize($tournament_id);
		
		$slug = "email_notify_tournament_finished_prize_rank_information";
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		
		foreach($prize_array as $item){
			$USER = $this->CI->user_tournament_entity->findUserHasARankInTournament($item->rank,$tournament_id);
			if($USER){
				$orgArr = array( "{###TOURNAMENT_NAME###}", "{###RANK###}", "{###PRIZE###}" );
				$rplArr = array( $TOURNAMENT->getName() , $item->rank, $item->prize );
				
				$body = str_replace( $orgArr , $rplArr , $template['body'] );
				$subject = $template['subject'];
				
				$this->setToEmail($USER->getEmail());
				$this->setSubject($subject);
				$this->setBody($body);
				
				$this->sendEmail();
			}
		}
	}
	
	
	// 6. send email to user notify weekly prize of tournament is finished and prize information
	// slug:
	function _sendEmailToUsers_notifyWeeklyPrizeFinished($prize_id){
		$PRIZE  = clone_ ($this->CI->week_prize_entity->init('id', $prize_id) );
		$CAT_PRIZE  = clone_ ($this->CI->week_prize_entity->init('id', $PRIZE->getCategoryId()) );
		$TOURNAMENT = $this->CI->tournament_entity->init('id', $PRIZE->tournament_id);
		
		$slug = "email_notify_weekly_prize_finished_prize_rank_information";
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		
		$user_info = explode('#',$PRIZE->getWinnerId());
		$USER = $this->CI->user_entity->init('id',$user_info[0]);
		if($USER){
			$orgArr = array( "{###TOURNAMENT_NAME###}", "{###RANK###}", "{###PRIZE###}" ,"{###FROM###}" , "{###TO###}" );
			$rplArr = array( $TOURNAMENT->getName() , $PRIZE->rank, $PRIZE->prize , 
								sysDateFormat($CAT_PRIZE->getStartTime()), sysDateFormat($CAT_PRIZE->getEndTime()) );
			
			$body = str_replace( $orgArr , $rplArr , $template['body'] );
			$subject = $template['subject'];
			
			$this->setToEmail($USER->getEmail());
			$this->setSubject($subject);
			$this->setBody($body);
			
			$this->sendEmail();
		}
		
	}
	
	// 6. send email to user verify email 
	// slug: verification_email_user_registration
	function _sendEmailToUser_verificationEmail($user_id){
		$USER = clone_( $this->CI->user_entity->init('id',$user_id) );
		$slug = "verification_email_user_registration";
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		
		$link = site_url("cricket/user/verify/")."?username=".$USER->getUserName()."&sid=".md5($USER->getId()) ;
		$blink = "<a href='{$link}'>{$link}</a>";
		
		$orgArr = array( "{###LINK###}" );
		$rplArr = array( $blink );
		$body = str_replace( $orgArr , $rplArr , $template['body'] );
		
		$subject = $template['subject'];
		
		$this->setToEmail($USER->getEmail());
		$this->setSubject($subject);
		$this->setBody($body);
		
		$this->sendEmail();
	}
	
	// 7. send email coupon code to user add credits from auction site
	// slug:send_couponcode_to_user_add_credits
	// slug:send_couponcode_to_user_add_credits_sms_temp
	function _sendEmailToUser_couponcodeFromAuctionAddCredits($coupon_id){
		$COUPON = $this->CI->coupon_entity->init('id',$coupon_id);
		$USER = $this->CI->user_entity->init('username',$COUPON->getUserName());
		
		//$this->CI->load->helper('file');
		//write_file('./uploads/couponexec.txt',$coupon_id.'-'.$USER->getId().PHP_EOL, 'a+');//
		
		$credits = $COUPON->getCredits();
		$coupon = $COUPON->getCode();
		$coins = $COUPON->getCoin();
		
		$slug = "send_couponcode_to_user_add_credits";
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		
		$orgArr = array( "{###NAME###}" , "{###COINS###}" , "{###COUPON###}" );
		$rplArr = array( $USER->getFullName() , $coins , $coupon );
		$body = str_replace( $orgArr , $rplArr , $template['body'] );
		
		$subject = $template['subject'];
		
		$this->setToEmail($USER->getEmail());
		$this->setSubject($subject);
		$this->setBody($body);
		
		$this->sendEmail2();
		
		/////////////////////////////////////////
		$slug = "send_couponcode_to_user_add_credits_sms_temp";
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		
		$orgArr = array( "{###NAME###}" , "{###COINS###}" , "{###COUPON###}" );
		$rplArr = array( $USER->getFullName() , $coins , $coupon );
		$body = str_replace( $orgArr , $rplArr , $template['body'] );
		
		$body = urlencode( strip_tags($body) ); 
		$foneNo = $USER->getMobile();
		sendSMS2($foneNo, $body);	
	}
	
	//end class
}	

